<template>
  <div class="UserLayout">
    <!-- 标题 -->
    <Title>
      <template #default>{{ title }}</template>
    </Title>
      <!-- 表格 -->
      <section class="contentLayout">
        <div class="user">
          <div style="display: flex;justify-content: right;align-items:center; vertical-align: top">
            <div class="tableSet1">
              <div>
                <el-tooltip  effect="dark" content="刷新" placement="top">
                  <el-button :type="'text'" @click="Refresh"><el-icon size="19" style="color: #1F1F1F"><RefreshRight/></el-icon></el-button>
                </el-tooltip>
              </div>
              <div>
                <el-tooltip  effect="dark" content="密度" placement="top">
                  <el-dropdown placement="bottom-start" trigger="click" size='large'>
                    <el-button type="text"><el-icon size="18" style="color: #1F1F1F"><Sort/></el-icon></el-button>
                    <template #dropdown>
                      <el-dropdown-menu >
                        <el-dropdown-item
                            @click="changeSize('默认')"
                            :style="{backgroundColor:active===true ?'#E6F7FF' : ''}">
                          默认
                        </el-dropdown-item>
                        <el-dropdown-item
                            @click="changeSize('中等')"
                            :style="{backgroundColor:active===true ?'#E6F7FF' : ''}">
                          中等
                        </el-dropdown-item>
                        <el-dropdown-item
                            @click="changeSize('紧凑')"
                            :style="{backgroundColor:active===true ?'#E6F7FF' : ''}">
                          紧凑
                        </el-dropdown-item>
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                </el-tooltip>
              </div>
              <div>
                <el-icon size="19"><Setting /></el-icon>
              </div>
            </div>
          </div>
          <el-table :data="userList.list" v-loading="loading" style="width: 100%" :size="tableSize">
            <el-table-column label="序号" prop="" align="left" width="60" type="index" id="1"/>
            <el-table-column label="用户名" prop="username" />
            <el-table-column label="头像" prop="">
              <template #default="{ row }">
                <el-button text type="primary">
                  <el-image
                      style="width: 32px; height: 25px"
                      :preview-teleported="true"
                      :src="row.avatar_url"
                      :zoom-rate="1.2"
                      :max-scale="7"
                      :min-scale="0.2"
                      :preview-src-list="[row.avatar_url]"
                      fit="cover"
                      hide-on-click-modal
                      z-index="999"
                  />
                </el-button>
              </template>
            </el-table-column>
            <el-table-column label="联系电话" prop="mobile" />
            <el-table-column label="角色" prop="role" />
            <el-table-column label="账号状态" prop="status">
              <template #default="{ row }">
                <el-button v-if="row.enable_status === 1" class="btn-on" size="small">启用</el-button>
                <el-button v-if="row.enable_status === 0" class="btn-off" size="small">禁用</el-button>
              </template>
            </el-table-column>
            <el-table-column label="注册时间" prop="register_date" />
            <el-table-column label="操作" prop="action">
              <template #default="{row}">
                <span @click="openFormVisible(row)" class="Edit">编辑</span>
                <span @click="handleDelete(row)" class="Delete">删除</span>
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页 -->
          <div style="display: flex;justify-content: right;padding: 10px" >
            <div class="pageText" style="float: left;margin: 5px 15px">
              第 {{ (AllPages.page - 1) * AllPages.per_page + 1 }} -
              <span v-if="AllPages.per_page*AllPages.page<=userList.total">{{AllPages.page*AllPages.per_page}}</span>
              <span v-else>{{userList.total}}</span>
               条 / 总共 {{ userList.total }} 条
            </div>
            <el-pagination
                :current-page="AllPages.page"
                :page-size="AllPages.per_page"
                :pager-count="3"
                background
                layout="prev, pager, next"
                :total="userList.total"
                size="small"
                @current-change="handleCurrentChange"
                @size-change="handleSizeChange"
                style="margin-top: 3px"
            />
          </div>
        </div>
      </section>

      <!-- 编辑对话框 -->
    <el-dialog class="dialogFormVisible" v-model="dialogFormVisible" :title="dialogTitle" width="640" :before-close="handleClose">
      <el-form ref="FormRef" :rules="rules" label-position="top" :label-width="formLabelWidth">
        <el-form-item prop="username" label="用户名" style="margin-top: 20px" clearable>
          <el-input autocomplete="off" clearable placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item prop="mobile" label="联系电话" clearable>
          <el-input autocomplete="off" clearable placeholder="请输入手机号码" />
        </el-form-item>
        <el-form-item class="inputWidth" prop="enable_status" label="账号状态">
          <el-select placeholder="请选择账号状态" clearable>
            <el-option label="禁用" value="0" />
            <el-option label="启用" value="1" />
          </el-select>
        </el-form-item>
        <el-form-item prop="avatar" label="账号头像" enctype="multipart/form-data">
          <el-upload
              class="avatar-uploader"
              ref="upload"
              action="https://recruit.aicase.xyz/api/boss/boss/avatar/upload"
              list-type="picture-card"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
              :limit="1"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" alt="" />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
              <span class="imgText">上传图片</span>
            </el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">取消</el-button>
          <el-button type="primary" @click="submitForm()">确定</el-button>
        </div>
      </template>
    </el-dialog>
    </div>

</template>

<script setup>
import {ref, reactive} from 'vue';
import {ElTable, ElTableColumn, ElPagination, ElDialog, ElMessage, ElMessageBox} from 'element-plus';
import { getUserList, UpdateUser, DeleteUser } from "@/network/user";
import Title from "components/public/Title";
import { useRoute } from "vue-router";
import {Plus, RefreshRight, Setting, Sort} from "@element-plus/icons-vue";

const route = useRoute();
const title = route.meta.title;

const userList =ref({
  list:[],
  total:0
})
const AllPages=reactive({
  page:1,
  per_page:10,
  total:0
})
const loading = ref(true)

const allUserList = () => {
  getUserList(AllPages).then((res)=>{
    const list = res.data.data.list;
    const total = res.data.meta.total;
    userList.value.list=list;
    userList.value.total=total;
    if (res.data.code===0){
      setTimeout(()=>{
        loading.value=false
      },600)
    }else {
      loading.value=true
    }
  })
}
allUserList()
////////////////////////////////
const editUser=ref({
  username:'',//用户名
  mobile:'', //手机号
  enable_status:1,//状态
  avatar:''//图像
})
///////////////////////////////
const dialogFormVisible = ref(false);
// 弹窗标题
const dialogTitle = ref("");
//表单行宽
const formLabelWidth = '140px'
//表单校验
const FormRef=ref()

//手机号校验
const validateMobile=(value,callback)=>{
  //不能为空
  if (value===''){
    callback(new Error('用户名是必填项'))
  }else {
    const PhoneNumber=/^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/
    PhoneNumber.test(value) ? callback() : callback(new Error('手机号格式不对，请输入正确的手机号'))
  }
}
//表单校验规则
const rules=reactive({
  username:[{ required: true, message: '请输入用户名', trigger: 'change' }],
  mobile:[{validator:validateMobile,trigger:'change',required: true}],
  enable_status:[{ required: true, trigger: 'change',message: '请选择账号状态'}],
  avatar:[{ required: true, trigger: 'change',message: '请上传头像'}]
})
const imageUrl = ref('')

/////////////////////////
const selectedRow=ref([])
const openFormVisible=(row)=>{
  dialogFormVisible.value=true
  dialogTitle.value='编辑求职者'
  selectedRow.value=row
  editUser.value={...row}
  if (row.enable_status===0){
    editUser.value.disable_status='禁用'
  }else {
    editUser.value.enable_status='启用'
  }
  console.log(row)
}
///////////////////////////////
//提交表单数据
const submitForm = async () => {
  const row= {...selectedRow.value}
  editUser.value=row
  const result=await UpdateUser(row.id)
  ElMessage.success(result.data.message ? result.data.message :'删除成功')
  allUserList()
}
///////////////////////////////

const cancel = () => {
  dialogFormVisible.value=false
}
const handleClose = () => {
  dialogFormVisible.value=false
}

//删除
const handleDelete = (row) => {
  ElMessageBox.confirm(
      '你确定要删除记录吗?',
      '删除记录',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(async () => {
        const result=await DeleteUser(row.id)
        ElMessage.success(result.data.message ? result.data.message :'删除成功')
        allUserList()
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '取消删除',
        })
      })
}
//////////////////////////
const handleCurrentChange = (val) => {
  AllPages.page=val
  loading.value=true
  allUserList()
}
const handleSizeChange = (val) => {
  AllPages.per_page=val
  AllPages.page=1
  loading.value=true
  allUserList()
}

//刷新
const Refresh= () => {
  loading.value=true
  allUserList()
}
//密度
const tableSize = ref('default')
const active = ref([false, true, false])  // 使用一个数组表示三个状态

const sizeMap = {
  '紧凑': ['small', [true, false, false]],
  '中等': ['default', [false, true, false]],
  '默认': ['large', [false, false, true]],
}

const changeSize = (size) => {
  const [newSize, newActive] = sizeMap[size] || sizeMap['中等']  // 默认值处理
  tableSize.value = newSize
  active.value = newActive
}


//////////////////////////
</script>

<style scoped lang="scss">
.user{
  background-color: white;
  padding: 0 24px;
}
.demo-pagination-block + .demo-pagination-block {
  margin-top: 10px;
}

.demo-pagination-block .demonstration {
  margin-bottom: 16px;
}

.btn-on {
  color: #389e0d;
  background: #f6ffed;
  border-color: #b7eb8f;
}

.btn-off {
  color: #cf1322;
  background: #fff1f0;
  border-color: #ffa39e;
}
.tableSet1 {
  padding: 10px 0;
  display: flex;
  justify-content: space-around;
  div {
    padding: 4px;
    display: flex;
    align-items: center;
    vertical-align: center;
  }
}
.Edit,.Delete{
  cursor: pointer;
  color:#1890ff;
  padding:0 5px ;
}
</style>
